package com.gsit.job.flows;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gsit.job.config.Config;
import com.gsit.job.domain.Person;
import com.gsit.job.services.PersonFileWriter;
import com.gsit.job.services.PersonService;
import com.gsit.job.services.UrlParser;


@Component
public class JobService extends FlowServiceAbs{
	
	@Autowired
	private PersonFileWriter fileWriter;
	
	@Autowired
	private UrlParser urlParser;
	
	@Autowired
	private PersonService personService;
	
	private Integer index =0;
	private Integer limit =3;
	
	
	protected void processTest(){
		List<String> urls = new ArrayList<String>();
		urls.add("http://recruiter.monsterindia.com/v2/resumedatabase/resume.html?resid=282817218&uid=123362856&&type=private&folderID=13789689&section=3&source=0&mosf=0&cn=0");
		urls.add("http://recruiter.monsterindia.com/v2/resumedatabase/resume.html?resid=28281748&uid=23362856&&type=private&folderID=13789689&section=3&source=0&mosf=0&cn=0");
		List<Person> persons = urlParser.parse( urls);
		
		
		for (Person person : persons) {
			personService.saveOrUpdate(person);
		/*	entityManager.persist(person);
			entityManager.flush();*/
			fileWriter.write(person, "this is first ");
		}
		System.out.println(personService.findAll().size());

	}
	
	
	
	
	
	//NEED to done on second step
	private void createFile(List<Person> persons){
		System.out.println("Persons are >>>>>>>>>>>>>>"+persons.size());
		
		/*for (Person person : persons) {
			doLoadResumeData(person);
		}*/
		
		doLoadResumeData(persons.get(0));
		doLoadResumeData(persons.get(1));
		doLoadResumeData(persons.get(2));
	}
	
	private List<Person> createPersonsFromUrl(List<String> urls){
		return urlParser.parse( urls);
		
	}

	private void doLoadResumeData(Person person) {
		StringBuilder st = new StringBuilder();
		st.append(Config.RESUME_URL);
		st.append("resid="+person.getResid());
		st.append("&uid="+person.getUid());
		driver.get(st.toString());
		fileWriter.write(person, driver.getPageSource());
		
	}


	protected void process() throws Exception{
		while (index < limit) {
			index++;
			doPageLoad();
		}
		
	}


	private void doPageLoad() {
		String path =Config.VINAY_FOLDER_PATH+index;
		driver.get(path);
		sleep(1000);
		List<String> urls = new ArrayList<String>();
		
		List<WebElement> link=driver.findElements(By.tagName("a"));

		for(WebElement ele:link){
			String id = ele.getAttribute("id");
			if(id.toLowerCase().startsWith("res_")){
				String href = ele.getAttribute("href");
				urls.add(href);
			}
		}
		personService.saveOrUpdate(urlParser.parse( urls));	
		sleep(2000);
		
	}
	
	



	


}
